<template>
  <div class="pay-order-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/cart' }">购物车</el-breadcrumb-item>
        <el-breadcrumb-item>订单支付</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">订单支付</h1>
    </div>
    
    <!-- 支付内容 -->
    <div v-if="!loading" class="pay-content">
      <!-- 订单不存在或加载失败 -->
      <div v-if="!order || order.status !== 'pending_payment'" class="order-error">
        <div class="error-icon">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="error-text">
          {{ order ? '订单已支付或状态异常' : '订单不存在或已被删除' }}
        </div>
        <el-button type="primary" @click="goBack" class="go-back-btn">
          返回
        </el-button>
      </div>
      
      <!-- 支付页面 -->
      <div v-else class="payment-page">
        <!-- 订单信息卡片 -->
        <div class="order-info-card">
          <div class="card-title">订单信息</div>
          <div class="card-content">
            <div class="order-number">订单编号：{{ order.id }}</div>
            <div class="order-time">创建时间：{{ order.createTime }}</div>
            <div class="order-amount">
              <span class="amount-label">支付金额：</span>
              <span class="amount-value">¥{{ getActualPayment().toFixed(2) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 支付方式选择 -->
        <div class="payment-method-section">
          <div class="section-title">选择支付方式</div>
          <div class="payment-methods">
            <div 
              v-for="method in paymentMethods" 
              :key="method.value"
              class="payment-method-item"
              :class="{ active: selectedMethod === method.value }"
              @click="handleMethodSelect(method.value)"
            >
              <div class="method-icon">
                <i :class="method.icon"></i>
              </div>
              <div class="method-info">
                <div class="method-name">{{ method.name }}</div>
                <div class="method-desc">{{ method.description }}</div>
              </div>
              <div class="method-check">
                <el-radio v-model="selectedMethod" :label="method.value" :border="false">
                </el-radio>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 支付操作 -->
        <div class="payment-action">
          <div v-if="!showQRCode && !paymentSuccess && !paymentError" class="action-content">
            <div class="amount-summary">
              <span class="summary-label">实付金额：</span>
              <span class="summary-value">¥{{ getActualPayment().toFixed(2) }}</span>
            </div>
            <el-button 
              type="primary" 
              @click="handlePayNow"
              :loading="processingPayment"
              class="pay-now-btn"
            >
              立即支付
            </el-button>
          </div>
          
          <!-- 二维码支付（微信支付和支付宝扫码） -->
          <div v-else-if="showQRCode" class="qr-code-container">
            <div class="qr-code-header">
              <h3 class="qr-title">{{ getSelectedMethodName() }}</h3>
              <el-button type="text" @click="cancelPayment" class="cancel-btn">
                取消支付
              </el-button>
            </div>
            <div class="qr-code-content">
              <div class="qr-code-image">
                <img :src="qrCodeImage" alt="支付二维码" />
              </div>
              <div class="qr-code-hint">
                请使用{{ getSelectedMethodName() }}扫描二维码完成支付
              </div>
              <div class="qr-code-countdown">
                支付倒计时：<span class="countdown-number">{{ countdown }}</span>秒
              </div>
              <div class="qr-code-notice">
                如二维码已过期，请点击「重新获取」
              </div>
              <div class="qr-code-actions">
                <el-button type="default" @click="refreshQRCode" class="refresh-btn">
                  重新获取
                </el-button>
                <el-button type="default" @click="checkPaymentResult" class="check-btn">
                  已完成支付
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 支付成功 -->
          <div v-else-if="paymentSuccess" class="payment-result success">
            <div class="result-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="result-title">支付成功</div>
            <div class="result-desc">您的订单已支付成功，感谢您的购买！</div>
            <div class="result-actions">
              <el-button type="default" @click="viewOrderDetail" class="detail-btn">
                查看订单
              </el-button>
              <el-button type="primary" @click="continueShopping" class="shopping-btn">
                继续购物
              </el-button>
            </div>
          </div>
          
          <!-- 支付失败 -->
          <div v-else-if="paymentError" class="payment-result error">
            <div class="result-icon">
              <el-icon><CircleClose /></el-icon>
            </div>
            <div class="result-title">支付失败</div>
            <div class="result-desc">{{ errorMessage || '支付过程中出现错误，请重试' }}</div>
            <div class="result-actions">
              <el-button type="default" @click="retryPayment" class="retry-btn">
                重新支付
              </el-button>
              <el-button type="default" @click="goBack" class="back-btn">
                返回订单列表
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useOrderStore } from '../../store/modules/order'
import { usePayStore } from '../../store/modules/pay'
import { useUserStore } from '../../store/modules/user'
import { ArrowRight, Warning, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const orderStore = useOrderStore()
const payStore = usePayStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const processingPayment = ref(false)
const order = ref(null)
const selectedMethod = ref('alipay') // 默认选择支付宝
const showQRCode = ref(false)
const paymentSuccess = ref(false)
const paymentError = ref(false)
const errorMessage = ref('')
const qrCodeImage = ref('')
const countdown = ref(180) // 3分钟倒计时
const countdownTimer = ref(null)

// 获取订单ID
const orderId = computed(() => route.params.id)

// 支付方式列表
const paymentMethods = ref([
  {
    value: 'alipay',
    name: '支付宝',
    description: '使用支付宝扫码支付',
    icon: 'el-icon-alipay'
  },
  {
    value: 'wechat',
    name: '微信支付',
    description: '使用微信扫码支付',
    icon: 'el-icon-wechat'
  },
  {
    value: 'bank',
    name: '银行卡支付',
    description: '使用储蓄卡/信用卡支付',
    icon: 'el-icon-credit-card'
  }
])

// 返回
const goBack = () => {
  if (order.value) {
    router.push('/order/list')
  } else {
    router.push('/')
  }
}

// 获取选中的支付方式名称
const getSelectedMethodName = () => {
  const method = paymentMethods.value.find(m => m.value === selectedMethod.value)
  return method ? method.name : ''
}

// 获取实际支付金额
const getActualPayment = () => {
  if (!order.value) return 0
  const discount = order.value.discountAmount || 0
  const shippingFee = order.value.shippingFee || 0
  return order.value.totalAmount - discount + shippingFee
}

// 处理支付方式选择
const handleMethodSelect = (method) => {
  selectedMethod.value = method
}

// 处理立即支付
const handlePayNow = async () => {
  if (!order.value) {
    ElMessage.error('订单信息异常，请刷新页面重试')
    return
  }
  
  processingPayment.value = true
  try {
    // 创建支付订单
    // const paymentResult = await payStore.createPayment({
    //   orderId: order.value.id,
    //   amount: getActualPayment(),
    //   paymentMethod: selectedMethod.value
    // })
    
    // 模拟支付处理
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 处理不同支付方式
    if (selectedMethod.value === 'alipay' || selectedMethod.value === 'wechat') {
      // 生成二维码（模拟）
      qrCodeImage.value = generateMockQRCode(selectedMethod.value)
      showQRCode.value = true
      startCountdown()
      
      // 启动轮询检查支付结果
      startPollingPaymentResult()
    } else if (selectedMethod.value === 'bank') {
      // 银行卡支付，跳转到支付页面或显示表单
      handleBankPayment()
    }
  } catch (error) {
    ElMessage.error('创建支付失败：' + error.message)
    errorMessage.value = error.message
    paymentError.value = true
  } finally {
    processingPayment.value = false
  }
}

// 处理银行卡支付
const handleBankPayment = () => {
  // 实际项目中这里应该跳转到银行卡支付页面或显示银行卡支付表单
  // 这里为了演示，我们直接模拟支付成功
  setTimeout(() => {
    paymentSuccess.value = true
  }, 1000)
}

// 生成模拟二维码
const generateMockQRCode = (method) => {
  // 在实际项目中，这里应该使用真实的二维码图片
  // 这里使用base64编码的简单图片作为示例
  if (method === 'alipay') {
    return '';
  } else {
    return '';
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 180
  
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  
  countdownTimer.value = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer.value)
      ElMessage.warning('支付已超时，请重新发起支付')
      cancelPayment()
    }
  }, 1000)
}

// 启动轮询检查支付结果
const startPollingPaymentResult = () => {
  // 模拟支付结果检查，实际项目中应该调用API检查
  const pollingTimer = setInterval(async () => {
    try {
      // 模拟支付成功的情况
      // 实际项目中应该调用 payStore.checkPaymentStatus(orderId.value)
      const success = Math.random() > 0.85 // 随机模拟支付成功
      
      if (success) {
        clearInterval(pollingTimer)
        paymentSuccess.value = true
        showQRCode.value = false
        
        // 更新订单状态
        await updateOrderStatus()
        
        ElMessage.success('支付成功')
      }
    } catch (error) {
      console.error('检查支付结果失败：', error)
    }
  }, 3000) // 每3秒检查一次
  
  // 3分钟后停止轮询
  setTimeout(() => {
    clearInterval(pollingTimer)
  }, 180000)
}

// 取消支付
const cancelPayment = () => {
  showQRCode.value = false
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
}

// 刷新二维码
const refreshQRCode = async () => {
  try {
    // 重新生成二维码
    qrCodeImage.value = generateMockQRCode(selectedMethod.value)
    startCountdown()
    ElMessage.success('二维码已刷新')
  } catch (error) {
    ElMessage.error('刷新二维码失败：' + error.message)
  }
}

// 检查支付结果（用户点击已完成支付）
const checkPaymentResult = async () => {
  try {
    processingPayment.value = true
    
    // 模拟检查支付结果
    // 实际项目中应该调用 payStore.checkPaymentStatus(orderId.value)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟支付成功
    paymentSuccess.value = true
    showQRCode.value = false
    
    // 更新订单状态
    await updateOrderStatus()
    
    ElMessage.success('支付成功')
  } catch (error) {
    ElMessage.error('支付结果检查失败：' + error.message)
    errorMessage.value = error.message
    paymentError.value = true
    showQRCode.value = false
  } finally {
    processingPayment.value = false
  }
}

// 更新订单状态
const updateOrderStatus = async () => {
  try {
    // 实际项目中应该调用 orderStore.updateOrderStatus(orderId.value, 'pending_shipment')
    // 这里仅做演示
    if (order.value) {
      order.value.status = 'pending_shipment'
      order.value.statusText = '待发货'
      order.value.paymentTime = new Date().toLocaleString('zh-CN')
    }
  } catch (error) {
    console.error('更新订单状态失败：', error)
  }
}

// 重试支付
const retryPayment = () => {
  paymentError.value = false
  errorMessage.value = ''
  selectedMethod.value = 'alipay'
}

// 查看订单详情
const viewOrderDetail = () => {
  if (order.value) {
    router.push(`/order/detail/${order.value.id}`)
  } else {
    router.push('/order/list')
  }
}

// 继续购物
const continueShopping = () => {
  router.push('/')
}

// 加载订单信息
const loadOrderInfo = async () => {
  loading.value = true
  try {
    // 检查用户是否登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    // 模拟API调用，实际项目中替换为真实API
    // const data = await orderStore.getOrderDetail(orderId.value)
    // order.value = data
    
    // 模拟订单数据
    order.value = generateMockOrder(orderId.value)
    
    // 检查订单状态是否为待支付
    if (order.value.status !== 'pending_payment') {
      ElMessage.warning('订单已支付或状态异常')
    }
  } catch (error) {
    ElMessage.error('加载订单信息失败：' + error.message)
    order.value = null
  } finally {
    loading.value = false
  }
}

// 生成模拟订单数据
const generateMockOrder = (orderId) => {
  return {
    id: orderId || 'ORD20231123003',
    createTime: '2023-11-23 19:45:50',
    totalAmount: 129,
    discountAmount: 0,
    shippingFee: 0,
    status: 'pending_payment',
    statusText: '待付款',
    items: [
      {
        id: 4,
        productId: 10,
        name: '无线充电器 15W快充',
        image: '/product/discount2.png',
        price: 129,
        quantity: 1,
        specs: { '颜色': '黑色' }
      }
    ],
    address: {
      name: '张三',
      phone: '138****1234',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detailAddress: '科技园南区8栋101室'
    },
    paymentMethod: 'alipay'
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadOrderInfo()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped>
.pay-order-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin: 20px 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: $font-size-xxl;
  color: $text-color;
  font-weight: bold;
  margin: 0;
}

/* 支付内容 */
.pay-content {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 0;
}

/* 订单错误 */
.order-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 40px;
}

.error-icon {
  font-size: 80px;
  color: $text-color-placeholder;
  margin-bottom: 20px;
}

.error-text {
  font-size: $font-size-base;
  color: $text-color-secondary;
  margin-bottom: 20px;
}

.go-back-btn {
  padding: 10px 30px;
  font-size: $font-size-base;
}

/* 支付页面 */
.payment-page {
  padding: 30px;
}

/* 订单信息卡片 */
.order-info-card {
  background-color: $primary-color-light;
  border-radius: $border-radius-base;
  padding: 20px;
  margin-bottom: 30px;
}

.card-title {
  font-size: $font-size-lg;
  color: $primary-color;
  font-weight: 500;
  margin-bottom: 15px;
}

.card-content {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: center;
}

.order-number,
.order-time {
  font-size: $font-size-base;
  color: $text-color-secondary;
}

.order-amount {
  display: flex;
  align-items: baseline;
  gap: 10px;
  margin-left: auto;
}

.amount-label {
  font-size: $font-size-base;
  color: $text-color;
}

.amount-value {
  font-size: $font-size-xl;
  color: $danger-color;
  font-weight: bold;
}

/* 支付方式选择 */
.payment-method-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: $font-size-lg;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid $border-color;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.payment-method-item {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 15px 20px;
  border: 2px solid $border-color;
  border-radius: $border-radius-base;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-method-item:hover {
  border-color: $primary-color;
  box-shadow: 0 0 0 2px $primary-color-light;
}

.payment-method-item.active {
  border-color: $primary-color;
  background-color: $primary-color-light;
}

.method-icon {
  font-size: $font-size-xl;
  color: $primary-color;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: $font-size-base;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 5px;
}

.method-desc {
  font-size: $font-size-sm;
  color: $text-color-secondary;
}

.method-check {
  margin-left: auto;
}

/* 支付操作 */
.payment-action {
  text-align: center;
  padding: 30px 0;
  border-top: 1px solid $border-color;
}

.action-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.amount-summary {
  display: flex;
  align-items: baseline;
  gap: 10px;
}

.summary-label {
  font-size: $font-size-base;
  color: $text-color;
}

.summary-value {
  font-size: $font-size-xxl;
  color: $danger-color;
  font-weight: bold;
}

.pay-now-btn {
  padding: 12px 48px;
  font-size: $font-size-base;
  background-color: $danger-color;
  border-color: $danger-color;
}

.pay-now-btn:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

/* 二维码支付 */
.qr-code-container {
  max-width: 400px;
  margin: 0 auto;
}

.qr-code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.qr-title {
  font-size: $font-size-lg;
  color: $text-color;
  font-weight: 500;
  margin: 0;
}

.cancel-btn {
  color: $text-color-secondary;
}

.qr-code-content {
  text-align: center;
}

.qr-code-image {
  width: 200px;
  height: 200px;
  margin: 0 auto 20px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid $border-color;
  border-radius: $border-radius-base;
}

.qr-code-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qr-code-hint {
  font-size: $font-size-base;
  color: $text-color;
  margin-bottom: 15px;
}

.qr-code-countdown {
  font-size: $font-size-base;
  color: $danger-color;
  margin-bottom: 15px;
}

.countdown-number {
  font-weight: bold;
  margin: 0 5px;
}

.qr-code-notice {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin-bottom: 20px;
}

.qr-code-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.refresh-btn,
.check-btn {
  padding: 8px 20px;
}

/* 支付结果 */
.payment-result {
  max-width: 400px;
  margin: 0 auto;
  padding: 40px 0;
}

.result-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.success .result-icon {
  color: $success-color;
}

.error .result-icon {
  color: $danger-color;
}

.result-title {
  font-size: $font-size-xl;
  color: $text-color;
  font-weight: 500;
  margin-bottom: 10px;
}

.result-desc {
  font-size: $font-size-base;
  color: $text-color-secondary;
  margin-bottom: 30px;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.detail-btn,
.back-btn,
.retry-btn {
  padding: 8px 20px;
}

.shopping-btn {
  padding: 8px 20px;
  background-color: $primary-color;
  border-color: $primary-color;
}

.shopping-btn:hover {
  background-color: #409eff;
  border-color: #409eff;
}

/* 加载状态 */
.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  /* 保持现有样式 */
}

@media (max-width: 992px) {
  .card-content {
    gap: 20px;
  }
  
  .order-amount {
    margin-left: 0;
  }
}

@media (max-width: 768px) {
  .pay-order-container {
    padding: 0 10px;
  }
  
  .payment-page {
    padding: 20px;
  }
  
  .action-content {
    justify-content: center;
  }
  
  .qr-code-image {
    width: 180px;
    height: 180px;
  }
  
  .result-icon {
    font-size: 60px;
  }
}

@media (max-width: 480px) {
  .card-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .payment-method-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 15px;
  }
  
  .method-check {
    margin-left: 0;
    align-self: flex-end;
  }
  
  .qr-code-header {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
  
  .qr-code-image {
    width: 160px;
    height: 160px;
  }
  
  .result-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .result-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
}
</style>